package com.socket.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.Map;

@Controller
public class WebSocketController2 {
    @Autowired
    private SimpMessagingTemplate template;

    @MessageMapping("/fromClient")
    @SendTo("/topic/toClient")//向客户端订阅的订阅号发送的消息，适用于接收客户端消息后的响应（类似于请求-响应）
    public String handle(String msg) {
        return "service to client";
    }

    @MessageMapping("/fromClient2")
    @SendTo("/toClient2")//向客户端订阅的订阅号发送的消息，适用于接收客户端消息后的响应（类似于请求-响应）
    public String toClient2(String msg) {
        return "service to client2";
    }

    /**
     * @SendTo 不适用于服务端主动发送消息
     * 主动发送消息可以使用SimpMessagingTemplate.convertAndSend();
     */
    @Scheduled(fixedRate = 5000)
    public void toClient() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "toClient");
        map.put("age", 20);
        //主动向客户端发送消息
        template.convertAndSend("/topic/toClient", map);
    }

    @Scheduled(fixedRate = 100)
    public void toClient2() {
        //主动向客户端发送消息
        template.convertAndSend("/topic/serverToClient", "每100毫秒向订阅了【/topic/serverToClient】的客户端发送消息");
    }
}

